package logic

import (
	"context"
	"fmt"
	"wechat/models/mysql"

	"wechat/userrpc/internal/svc"
	"wechat/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserFriendLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserFriendLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserFriendLogic {
	return &UserFriendLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserFriendLogic) UserFriend(in *userrpc.UserFriendRequest) (*userrpc.UserFriendResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	mysql.DB.Where("id = ?", in.UserId).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("当前用户不存在")
	}

	var friendUsers []mysql.FriendUser

	if in.GroupId != 0 {
		mysql.DB.Raw("select friends.friend_id, users.name, users.head_image from friends LEFT JOIN  users on users.id = friends.friend_id  LEFT JOIN group_users ON users.id =  group_users.friend_id where friends.user_id = ?  and group_users.group_id = ? and friends.deleted_at is null", in.UserId, in.GroupId).Scan(&friendUsers)
	} else {
		mysql.DB.Raw("select friends.friend_id, users.name, users.head_image from friends LEFT JOIN  users on users.id = friends.friend_id  where user_id = ? and friends.deleted_at is null", in.UserId).Scan(&friendUsers)
	}

	var userFriends []*userrpc.UserFriend

	for _, friend := range friendUsers {
		list := userrpc.UserFriend{
			FriendId:  friend.FriendId,
			HeadImage: friend.HeadImage,
			Name:      friend.Name,
		}

		userFriends = append(userFriends, &list)
	}
	return &userrpc.UserFriendResponse{List: userFriends}, nil
}
